package y2016.date0302.am.下载硬笔书法网;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Download {
    List<String> linkList;

    public Download() {
    }

    public List<String> getLinkListFromHtm() {
        if (linkList == null) {
            linkList = new ArrayList<>();
        }
        try {
            Document document = Jsoup.parse(new File("src/date0302/am/index.htm"), "gbk");
            Elements elements = document.getElementsByAttribute("target");
            for (Iterator iterator = elements.iterator(); iterator.hasNext(); ) {
                Element e = (Element) iterator.next();
                String link = e.attr("href");
                System.out.println(link);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return linkList;
    }

    private String[] getLinkFromTxt(int mode) {
        if (linkList == null) {
            linkList = new ArrayList<>();
        }
        if (linkList.size() != 0) {
            linkList.clear();
        }
        File file = new File("src/date0302/am/link.txt");
        try {
            InputStream is = new FileInputStream(file);
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            char ch[] = new char[1024];
            StringBuilder sb = new StringBuilder();
            int len;
            while ((len = br.read(ch)) != -1) {
                sb.append(new String(ch, 0, len));
            }
            String[] str = sb.toString().split("【】");
            switch (mode) {
                case 1:
                    return str[0].split("\n");
                case 2:
                    return str[1].split("\n");
                case 3:
                    return str[2].split("\n");
                case 4:
                    return str[3].split("\n");
                case 5:
                    return str[4].split("\n");
                default:
                    break;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void getImageFromInternet(int mode) {
        String[] strs = getLinkFromTxt(mode);
        for (int i = 0; i < strs.length; i++) {
//			System.out.println(strs[i]);
            String link = "http://yingbishufa.eshufa.com/ZUOPIN/ldmp/" + strs[i];
            String imageLink = null;
            try {
                Document document = Jsoup.connect(link).get();
                Elements elements = document.getElementsByAttribute("target");
                for (Iterator iterator = elements.iterator(); iterator.hasNext(); ) {
                    Element element = (Element) iterator.next();
                    String str = element.attr("href");
                    int index = 0;
                    if (str.contains("ZUOPIN")) {
                        index = str.indexOf("Z");
                        str = str.substring(index, str.length());
                        imageLink = "http://yingbishufa.eshufa.com/" + str;
                    } else if (str.contains("ZPXS")) {
                        index = str.indexOf("Z");
                        str = str.substring(index, str.length());
                        imageLink = "http://yingbishufa.eshufa.com/ZUOPIN/" + str;
                    } else if (str.contains("JPG")) {
//						str = str.substring(index, str.length());
                        imageLink =
                                "http://yingbishufa.eshufa.com/ZUOPIN/ldmp/yylj/" + str;
                        System.out.println(imageLink);
                    }
                    downloada("D:\\名家", imageLink);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 执行下载并保存文件
     *
     * @param downloadFile
     * @param imageLink
     */
    private void downloada(String pathname, String imageLink) {
        if (imageLink == null) {
            return;
        }
        if (!imageLink.endsWith("jpg") && !imageLink.endsWith("JPG")) {
            return;
        }
        String fileName = imageLink.substring(imageLink.lastIndexOf("/"));
        File downloadFile = new File(pathname + fileName);
        if (downloadFile.exists()) {
            return;
        }

        downloadFile.getParentFile().mkdirs();
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        URL url;
        try {
            url = new URL(imageLink);
            URLConnection conn = url.openConnection();
            in = new BufferedInputStream(conn.getInputStream());
            out = new BufferedOutputStream(new FileOutputStream(downloadFile));
            int b;
            byte buffer[] = new byte[10 * 1024];
            while ((b = in.read(buffer)) != -1) {
                out.write(buffer, 0, b);
            }
            out.flush();
            out.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("\n\n文件" + downloadFile.getName() + "下载完成，保存到：\n" + downloadFile.getParent());
    }


}


